package com.pasabahceambalaj.session;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

import com.pasabahceambalaj.entity.Firma;
import com.pasabahceambalaj.entity.Kullanici;
import com.pasabahceambalaj.entity.Rol;

@Name("authenticator")
public class Authenticator {
	@Logger
	private Log log;
	
	@In
	EntityManager entityManager;
	
	@In
	Identity identity;
	
	@In
	Credentials credentials;

	public boolean authenticate() {
		log.info("authenticating {0}", credentials.getUsername());

		try {
			Kullanici user = (Kullanici) entityManager.createQuery("from Kullanici where kod = :username and parola = :password").setParameter("username", credentials.getUsername()).setParameter("password", credentials.getPassword()).getSingleResult();

			if (user.getRols() != null) {
				for (Rol rol : user.getRols()) {
					identity.addRole(rol.getKod());
					Contexts.getSessionContext().set("user", user);
					log.info("eklenen rol : {0}", rol.getKod());
				}
			}

			if (user != null && user.getId() != null) {
				log.info("{0}", user.getFirma().getAd());
				return true;
			} else {
				return false;
			}
		} catch (NoResultException ex) {
			return false;
		}
	}

	public static boolean isAdmin() {
		return Identity.instance().hasRole("admin");
	}

	public static Firma getFirma(){
		Kullanici user = (Kullanici) Contexts.getSessionContext().get("user");
		return user.getFirma();
	}
	
	public static boolean isLoggedIn() {
		return Identity.instance().isLoggedIn();
	}
}